package tedu.week04.day02_thread.lesson3;

/**
 * <pre>
 *      死锁问题的产生及解决.
 *
 * </pre>
 *
 * @author : resty
 * @date : 2019年07月09日    13时
 **/
public class LockThread implements Runnable{
    private static FuWong fw = new FuWong();
    private static QiangDao qd = new QiangDao();
    public boolean flag;
    @Override
    public void run() {
        if(flag){//true富翁说
            synchronized (fw){
                fw.say();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (qd){
                    fw.give();
                }
            }
        }else{//强盗说
            synchronized (qd){
                qd.say();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (fw){
                    qd.give();
                }
            }
        }
    }
    public static void main(String[] args){
        LockThread fu = new LockThread();
        LockThread qi = new LockThread();
        fu.flag = true;
        qi.flag = false;
        Thread t1 = new Thread(fu);
        Thread t2 = new Thread(qi);
        t1.start();
        t2.start();
    }
}

class FuWong{
    public void say(){
        System.out.println("富翁说:把儿子交给我,我给你钱.");
    }
    public void give(){
        System.out.println("富翁把钱给了强盗...");

    }
}
class QiangDao{
    public void say(){
        System.out.println("强盗说:给我钱.把儿子给你..");
    }
    public void give(){
        System.out.println("强盗把钱给了富翁...");
    }
}

